﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common.Security
{
    public class RsaHelper
    {
        /// <summary>
        /// 产生加密解密密钥对
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> CreateRsaKeyPair()
        {
            var keyPair = new Dictionary<string, string>();
            var rsaProvider = new RSACryptoServiceProvider(1024);
            RSAParameters parameter = rsaProvider.ExportParameters(true);
            keyPair.Add("PUBLIC", BytesToHexString(parameter.Exponent) + "," + BytesToHexString(parameter.Modulus));
            keyPair.Add("PRIVATE", rsaProvider.ToXmlString(true));
            return keyPair;
        }

        /// <summary>
        /// RSA解密字符串
        /// </summary>
        /// <param name="encryptData">密文</param>
        /// <param name="privateKey">私钥</param>
        /// <returns>明文</returns>
        public static string DecryptRsa(string encryptData, string privateKey)
        {
            string decryptData = "";
            try
            {
                var provider = new RSACryptoServiceProvider();
                provider.FromXmlString(privateKey);

                byte[] result = provider.Decrypt(HexStringToBytes(encryptData), false);
                ASCIIEncoding enc = new ASCIIEncoding();
                decryptData = enc.GetString(result);
            }
            catch (Exception e)
            {
                throw new Exception("RSA解密出错!", e);
            }
            return decryptData;
        }



        public static byte[] HexStringToBytes(string hex)
        {
            if (hex.Length == 0)
            {
                return new byte[] { 0 };
            }

            if (hex.Length % 2 == 1)
            {
                hex = "0" + hex;
            }

            byte[] result = new byte[hex.Length / 2];

            for (int i = 0; i < hex.Length / 2; i++)
            {
                result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static string BytesToHexString(byte[] input)
        {
            StringBuilder hexString = new StringBuilder(64);

            for (int i = 0; i < input.Length; i++)
            {
                hexString.Append(string.Format("{0:X2}", input[i]));
            }
            return hexString.ToString();
        }
    }
}
